// 简易后台管理
var express = require('express')
var express = require('express')
// 导入 mysql
var mysql = require('mysql')
// 导入 uuid
var uuid = require('uuid')
var multipart=require('connect-multiparty');
var fs = require('fs')
var multipartMidd=multipart();
// 引入日期格式化工具
var getData = require('../utils/getDate')

var router = express.Router()

// 创建数据库连接池
var pool   = mysql.createPool({
    host     : '127.0.0.1',
    user     : 'root',
    password : '123',
    database : 'bighomework'
});


// 主页
router.get('/admin',function(req,res){
    res.render('index.html')
})

// 添加博客
router.get('/admin/add/article',function(req,res){
    res.render('add_article.html',{
        date:getData('YYYY-mm-dd HH:MM:SS', new Date())
    })
})


// 添加话题
router.get('/admin/add/topic', function(req, res){
    res.render('add_topic.html')
}) 

// 处理添加话题
router.post('/admin/add/topic',multipartMidd,async function(req, res){
    // 获取参数
    const {name} = req.body
    const {topic_pic} = req.files
    // uuid
    const id = uuid.v4()
    // console.log(name, topic_pic)
    // 热度默认为0
    let heat = 0
    // 写文件，返回
    let topic_pic_url = await writeFilePromise(topic_pic)
    // console.log(topic_pic_url)
    // 构建添加对象
    let result = {
        id: id,
        name: name,
        heat : heat,
        topic_pic_url: topic_pic_url
    }
    // 写入数据库
    await insertArticlePromise()
    res.send({success:true})


    // 写文件 promise
    function writeFilePromise(file){
        return new Promise(resolve=>{
            // 将临时目录中的文件移动到cover
            var readStream=fs.createReadStream(file.path);
            var writeStream=fs.createWriteStream("./public/topic/"+id+file.name);
            readStream.pipe(writeStream);
            readStream.on('end',function(){
                fs.unlinkSync(file.path);
                // 将路径添加到reqBody中
                resolve(id+file.name)
            });
        })
    }

    // 操作数据库 promise
    function insertArticlePromise(){
        return new Promise(resolve=>{
            // 添加到数据库中
            pool.query("INSERT INTO topic set ?",result,(err, result)=>{
                if(err) {
                    return res.status(500).send({success:false})
                }
                // console.log(result)
                resolve(result)
            })
        })
    }
})




module.exports = router
